package top.csjss.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.csjss.domain.Users;
import top.csjss.domain.UsersExample;
import top.csjss.mapper.UsersMapper;
import top.csjss.service.UserService;

import java.util.List;

/**
 * @Author ztf
 * @Date 17:29 2021/10/7
 **/
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UsersMapper usersMapper;
    @Override
    public List<Users> login(String username, String password) {
        UsersExample usersExample=new UsersExample();
        UsersExample.Criteria criteria = usersExample.createCriteria();
        criteria.andNameEqualTo(username);
        criteria.andPasswordEqualTo(password);
        return usersMapper.selectByExample(usersExample);
    }

    @Override
    public PageInfo<Users> selectAllUsers(Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        List<Users> list= usersMapper.selectByExample(null);
        PageInfo<Users> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    @Override
    public PageInfo<Users> selectByUserName(Integer pageNum, Integer pageSize, String username) {
        PageHelper.startPage(pageNum,pageSize);
        UsersExample usersExample=new UsersExample();
        UsersExample.Criteria criteria = usersExample.createCriteria();
        criteria.andNameEqualTo(username);
        List<Users> list= usersMapper.selectByExample(usersExample);
        PageInfo<Users> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void updatePwd(Integer uid, String oldPwd, String newPwd) {
        Users users = usersMapper.selectByPrimaryKey(uid);
        if (!users.getPassword().equals(oldPwd)){
            System.out.println("旧密码输入错误");
            throw new RuntimeException("旧密码输入错误");
        }
        users.setPassword(newPwd);
        int i = usersMapper.updateByPrimaryKeySelective(users);
        if (i!=1){
            System.out.println("密码修改失败");
            throw new RuntimeException("密码修改失败");
        }
    }
}
